package com.leyou.page.service;

import com.leyou.common.enums.LyExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class PageServiceImpl implements PageService {

    @Autowired
    private ItemClient itemClient;

    @Override
    public Map<String, Object> loadData(Long id) {
        //查询spu spuDetail skus
        SpuDTO spu = itemClient.querySpuBySpuId(id);
        //根据分类id查询商品分类
        List<CategoryDTO> categories = itemClient.queryByCategoryIds(spu.getCategoryIds());
        //根据id查询品牌
        BrandDTO brand = itemClient.queryById(spu.getBrandId());
        //根据分类id查询specs：包含规格组及组内的规格参数
        List<SpecGroupDTO> specs = itemClient.querySpecGroupByCid(spu.getCid3());

        // 封装数据
        Map<String, Object> data = new HashMap<>();
        data.put("categories", categories);
        data.put("brand", brand);
        data.put("spuName", spu.getName());
        data.put("subTitle", spu.getSubTitle());
        data.put("skus", spu.getSkus());
        data.put("detail", spu.getSpuDetail());
        data.put("specs", specs);
        return data;
    }
    //spel
    @Value("${ly.static.itemDir}")
    private String itemDir;

    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;

    @Autowired
    private SpringTemplateEngine templateEngine;

    @Override
    public void createItemHtml(Long id) {
        //准备上下午对象
        Context context = new Context();
        //准备模型数据
        context.setVariables(loadData(id));
        //准备静态页生成的文件目录
        File dirFile = new File(itemDir);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        //指定生成的静态页  参数一：文件生成的目录 参数二：文件名称
        File htmlFile = new File(dirFile,id+".html");
        try {
            Writer writer = new PrintWriter(htmlFile,"utf-8");
            //基于模板引擎，将模型数据和模板对象结合，生成html页面
            templateEngine.process(itemTemplate,context,writer);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(LyExceptionEnum.FILE_WRITER_ERROR);
        }

    }

    @Override
    public void deleteItemHtml(Long id) {
        //准备静态页生成的文件目录
       // File dirFile = new File(itemDir);
        File htmlFile = new File(itemDir,id+".html");
        boolean result = htmlFile.delete();
        if(!result){
            throw new LyException(LyExceptionEnum.DELETE_OPERATION_FAIL);
        }
    }
}
